﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using aDream.Domain;

namespace aDream
{
    public class Propertys
    {
        private List<Property> properties = new List<Property>();
        private DataConnection connection;

        public Propertys(DataConnection connection)
        {
            this.connection = connection;
        }
      
        public Property property(int id)
        {
            foreach (Property property in properties)
                if (property.matches(id))
                    return property;
            return null;
        }

        public void addNewProperty(String type, String description, String details, String streetNo, String streetName, String suburb, String postCode, String state)
        {
            int nextInsertId = setNextInsert();
            String sql1 = "Insert into Property(idProperty, type, description, details) values(" + nextInsertId + ", '" + type + "', '" + description + "', '" + details + "');";
            String sql2 = "Insert into Address(idAddress, idProperty, streetNo, streetName, suburb, postCode, state) values (" + nextInsertId + ", " + nextInsertId + ", '" + streetNo + "', '" + streetName + "', '" + suburb + "', '" + postCode + "', '" + state + "');";
            connection.ExecuteNonReturningQuery(sql1);
            connection.ExecuteNonReturningQuery(sql2);
            add(nextInsertId, type, description, description, streetNo, streetName, suburb, postCode, state);
        }



        public void add(int id, String type, String description, String details, String streetNo, String streetName, String suburb, String postCode, String state)
        {
            Address address = new Address(streetNo, streetName, suburb, postCode, state);
            properties.Add(new Property(id, type, description, details, address));


        }

        public int setNextInsert()
        {
            DataTable dt;
            dt = connection.ExecuteReturningQuery("select max(idProperty) from Property; ");
            return Convert.ToInt32(dt.Rows[0].ItemArray[0].ToString()) + 1;
        }

        public List<Property> getProperties()
        {

            return properties;
        }

        public void delete(int id)
        {
            String stringSql = "Delete from Property where idProperty =" + id + ";";
            connection.ExecuteNonReturningQuery(stringSql);
            properties.Remove(property(id));
            
        }
    }
}
